// pages/contact/contact.js
import env from "../../utils/env";
const app = getApp()
Page({
  data: {
    isAuth: false,
    uPrice: 1,
    src: '',
    deviceposition: 'front',
    type: '',
    photoId: ''
  },
  onLoad(options) {
    this.setData({
      src: options.src,
      type: options.type
    })
    const _this = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.camera']) {
          // 用户已经授权
          _this.setData({
            isAuth: true
          })
        } else {
          // 用户还没有授权，向用户发起授权请求
          wx.authorize({
            scope: 'scope.camera',
            success() { // 用户同意授权
              _this.setData({
                isAuth: true
              })
            },
            fail() { // 用户不同意授权
              _this.openSetting().then(res => {
                _this.setData({
                  isAuth: true
                })
              })
            }
          })
        }
      },
      fail: res => {
        console.log('获取用户授权信息失败')
      }
    })
  },

  // 打开授权设置界面
  openSetting() {
    const _this = this
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: '授权',
        content: '请先授权获取摄像头权限',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                  resolve(true)
                } else { // 用户没有打开授权开关， 继续打开设置页面
                  _this.openSetting().then(res => {
                    resolve(true)
                  })
                }
              },
              fail(res) {
                console.log(res)
              }
            })
          } else if (res.cancel) {
            _this.openSetting().then(res => {
              resolve(true)
            })
          }
        }
      })
    })
    return promise;
  },

  // 拍照
  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath
        })
        this.uploadImage();
      }
    })
  },
  uploadImage() {
    const _this = this;
    const thirdSession = wx.getStorageSync('third_session');
    wx.showLoading({
      title: '靓照处理中，请稍后',
      mask: true
    })
    wx.uploadFile({
      url: env.api_host + '/identify/uploadImage',
      filePath: _this.data.src,
      name: 'file',
      formData: {
        type: _this.data.type,
        imgtype: 'store',
        thirdSession: thirdSession
      },
      success(res) {
        var obj = JSON.parse(res.data);
        if (obj.code == -3) {
          wx.showModal({
            title: '温馨提示',
            content: '当前位置无法裁剪证件照，请稍微远离摄像头再拍摄',
            showCancel: false,
          })
        } else if (obj.code == 500) {
          wx.showModal({
            title: '温馨提示',
            content: '当前服务器没有响应，请稍后再试',
            showCancel: false,
          })
        } else if (obj.code == -1 || obj.code == -2) {
          wx.showModal({
            title: '温馨提示',
            content: '您提供的照片检测不到符合要求的头像，请重新上传照片或拍摄',
            showCancel: false,
          })
        } else if (obj.code == 0) {
          var base64Image = "data:image/jpeg;base64," + obj.image; // 后台返回的base64数据
          var imgData = base64Image.replace(/[\r\n]/g, '') // 将回车换行换为空字符''
          _this.setData({
            src: imgData,
            photoId: obj.photoId
          })
        }

      },
      fail() {
        console.log("fail");
      },
      complete() {
        //添加wx.hideLoading()一定要添加到complete里
        wx.hideLoading()
      }
    });
  },
  reTakePhoto() {
    this.setData({
      src: ''
    })
  },
  goAlbum() {
    var that = this;
    wx.chooseMedia({
      count: 1,
      sizeType:['compressed'],
      mediaType: ['image'],
      sourceType: ['album'],
      maxDuration: 30,
      success(res) {
        wx.showToast({ title: '靓照处理中，请稍后', icon: 'loading', duration: 3000 });
        var fileUrl = res.tempFiles[0].tempFilePath;
        wx.navigateTo({
          //目的页面地址
          url: '/pages/preview/index?src=' + fileUrl + '&type=' + that.data.type,
        })
      }
    })
  },

  //使用前置摄像头/后置
  cameraPosition() {
    var that = this;
    if (that.data.cameraPosition == 'back') {
      that.setData({
        cameraPosition: 'front'
      })
    } else {
      that.setData({
        cameraPosition: 'back'
      })
    }
  },
  generateOrder() {
    wx.navigateTo({
      //目的页面地址
      url: '/pages/orderPreview/index?type=' + this.data.type + "&photoId=" + this.data.photoId,
    })
  },
  // 点击下载图片事件
  downloadImage() {
    wx.showLoading({
      title: '加载中...'
    });
    //wx.downloadFile方法：下载文件资源到本地
    wx.downloadFile({
      url: this.data.imgUrl, //图片地址
      success: function (res) {
        console.log(res);
        wx.saveImageToPhotosAlbum({//wx.saveImageToPhotosAlbum方法：保存图片到系统相册
          filePath: res.tempFilePath, //图片文件路径
          success: function (data) {
            wx.hideLoading(); //隐藏 loading 提示框
            wx.showModal({
              title: '温馨提示',
              content: '保存成功',
              modalType: false,
            })
          },
          // 接口调用失败的回调函数
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
              wx.showModal({
                title: '温馨提示',
                content: '需要您授权保存相册',
                modalType: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '温馨提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          modalType: false,
                        })
                      } else {
                        wx.showModal({
                          title: '温馨提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          modalType: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          },
          complete(res) {
            wx.hideLoading(); //隐藏 loading 提示框
          }
        })
      }
    })
  },
  /**生成商户订单 */
  generateOrder1() {
    var third_session = wx.getStorageSync('third_session');
    var Authorization = wx.getStorageSync('access_token');
    var that = this;
    var priceTemp = that.data.uPrice;
    var orderInfo = { "gName": '照片处理服务费', "product": '照片处理服务费', "orderType": '2', "photoId": that.data.photoId, "gPrice": priceTemp, "thirdSession": third_session, "amount": that.data.uPrice }
    console.log(orderInfo);
    console.log(Authorization);    //统一支付
    wx.request({
      url: env.api_host + '/identify/miniGenerateOrder1',
      method: 'GET',
      header: {
        Authorization: Authorization,
      },
      data: {
        orderInfo: orderInfo,
      },
      success: function (res) {
        var resResult = res.data;
        if (resResult.code == 200) {
          console.log(resResult);
          var payInfo = resResult.data;
          //发起支付
          var param = {
            "timeStamp": payInfo.timeStamp,
            "package": payInfo.package,
            "paySign": payInfo.sign,
            "signType": "RSA",
            "nonceStr": payInfo.nonceStr,
            "priceTemp": priceTemp,
            "prepayId": payInfo.prepayId,
            "appId": payInfo.appId,
            "openId": payInfo.openId
          };
          that.pay(param);
        } else if (resResult.code == 500) {
          wx.showModal({
            title: '温馨提示',
            content: '服务器内部错误，请在【我的】->【联系我们】中反馈',
            complete: (res) => {
              if (res.cancel) {
              }
              if (res.confirm) {
              }
            }
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '服务器没有响应，请在【我的】->【联系我们】中反馈',
            complete: (res) => {
              if (res.cancel) {
              }
              if (res.confirm) {
              }
            }
          })
        }
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },

  /* 支付  */
  pay: function (param) {
    var prepayId = "prepay_id=" + param.prepayId;
    var _this = this;
    wx.requestPayment({
      openId: param.openId,
      appId: param.prepayId,
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: prepayId,
      signType: "RSA",
      paySign: param.paySign,
      success: function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'fail',
          duration: 2000
        });
        _this.downloadPhoto(_this.data.photoId);
        wx.navigateTo({
          url: '/pages/order/index',
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '支付失败',
          icon: 'fail',
          duration: 2000
        })
      },
      complete: function () {
      }
    })
  },
  downloadPhoto(photoId) {
    var _this = this;
    var Authorization = wx.getStorageSync('access_token');
    wx.request({
      url: env.api_host + '/identify/photo/downloadPhoto/' + _this.data.photoId,
      method: 'GET',
      header: {
        Authorization: Authorization,
      },
      success: function (res) {
        if (res.statusCode == 200) {
          var resultData = res.data;
          if (resultData.code == 200) {
            var photoNoWater = resultData.data.cerPhoto;
            _this.savePhoto(photoNoWater);
          }
        }
      },
      fail: function (res) {
        console.log("downloadPhoto fail ");
      },
      complete: function (res) {
        console.log("downloadPhoto complete");

      }
    })
  },
  savePhoto: function (imgSrc) {
    var save = wx.getFileSystemManager();
    var number = Math.random();
    save.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.jpg',
      data: imgSrc,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.jpg',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
              //当初用户拒绝，再次发起授权
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: () => {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击按钮即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          },
        })
      }, fail: err => {
        console.log(err)
      }
    })
  },
  
  downloadDigitalPhoto() {
    if (!wx.getStorageSync('is_login')) {
      app.login();
    }else if(wx.getStorageSync('is_login')){
      wx.checkSession({
        success: (res) => {
          console.log("session valid");
        },
        fail: (res) => {
          console.log("session invalid");
          app.login();
        },
        complete: (res) => {},
      })
    }
    this.generateOrder1();
  }
})